package swu.cx.lock

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Point
import android.graphics.Rect
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.*
import android.widget.ImageView
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream

class MainActivity : AppCompatActivity() {
    private val views:Array<ImageView> by lazy {
         arrayOf(sDot1,sDot2,sDot3,sDot4,sDot5,sDot6,sDot7,sDot8,sDot9)
    }
    //计算状态栏的高度
    private val barHeight:Int by lazy {
        val display=DisplayMetrics()
         windowManager.defaultDisplay.getMetrics(display)
        val containerRect=Rect()
        window.findViewById<ViewGroup>(Window.ID_ANDROID_CONTENT).getDrawingRect(containerRect)
        return@lazy display.heightPixels-containerRect.height()
    }
    //记录密码
    val builder=StringBuilder()
    //记录电亮的控件
    val doneView= mutableListOf<ImageView>()
    //记录上一个被点亮的点
    var lastSDot:ImageView?=null
    //保存所有线的tag值
    private val allLineTags= arrayOf(
        12,23,45,56,78,89,//横线
        14,25,36,47,58,69, //竖线
        24,35,57,68,15,26,48,59//斜线
    )
    //记录原始密码
    private var orgPwd:String?=null
    //记录第一次设置的密码
    private var FirstPwd:String?=null
    //请求码
    private val REQUEST_IMAGE_CODE=123
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //获取密码
        SharedPreference.getInstance(this).getPwd().also {
            if (it==null){
                Tip.text="请设置密码图案"
            }else{
                Tip.text="请解锁密码图案"
                orgPwd=it
            }
        }
        mHeader.setOnClickListener {
            //从相册中读取一张图片
            Intent().apply {
                action=Intent.ACTION_PICK
                type="image/*"
                startActivityForResult(this,REQUEST_IMAGE_CODE)
            }
        }
        //获取头像
        File(filesDir,"header.jpg").also {
            if (it.exists()){
                BitmapFactory.decodeFile(it.path).also {image->
                    mHeader.setImageBitmap(image)
            }
        }
        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode){
            REQUEST_IMAGE_CODE->{
                //判断用户是否取消操作
                if (resultCode!=Activity.RESULT_CANCELED){
                    //获取图片
                    val uri=data?.data
                    data?.let {
                        //对IO操作尽量使用use
                        contentResolver.openInputStream(uri!!).use {
                            BitmapFactory.decodeStream(it).also {image->
                                //显示图片
                                mHeader.setImageBitmap(image)
                                //缓存图片
                                val file=File(filesDir,"header.jpg")
                                FileOutputStream(file).also {fos->
                                    image.compress(Bitmap.CompressFormat.JPEG,50,fos)
                                }
                                }
                            }
                        }
                    }

                }
            }
        }
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        val location=getLocationOnCons(event)
        //判断是否在操作区域内
        if (!((location.x>=0&&location.x<=mContainer.width)&&
            (location.y>=0&&location.y<=mContainer.height))) {
                //直接不进行下面操作
            return true
        }

        when(event?.action){
            MotionEvent.ACTION_DOWN->{
                isContained(location).also {
                    hightLight(it)
                }
            }
            MotionEvent.ACTION_MOVE->{
                isContained(location).also {
                    hightLight(it)
                }
            }
            MotionEvent.ACTION_UP->{
                //判断是不是第一次进入app
                if (orgPwd==null){
                    //是不是第一次设置密码
                    if(FirstPwd==null){
                        FirstPwd=builder.toString()
                        Tip.text="请再次确认密码"
                    }else{
                        //确认密码
                      //  Log.v("cx","----确认密码----")
                        comParePwd(FirstPwd!!,builder.toString())
                    }
                }else{
                    //确认密码
                    comParePwd(orgPwd!!,builder.toString())
                }
                recoverUI()
            }
        }
        return true
    }
    fun comParePwd(first:String,second:String){
        if (first==second){
            //两次密码一致
            if(orgPwd==null) Tip.text="设置密码成功" else Tip.text="登录成功！"
            SharedPreference.getInstance(this).savePwd(first)
        }else{
            if(orgPwd==null) Tip.text="两次密码不一致，请重新设置密码！！" else Tip.text="密码错误！"
            FirstPwd=null
        }
    }
    fun hightLight(v: ImageView?){
        if ((mHeader!=null)&&(v?.visibility==View.INVISIBLE)){
            //判断是不是第一个点
            if(lastSDot==null){
               hightLightDot(v)
            }else{
                //不是第一个，可以连线
                val previous=lastSDot?.tag.toString().toInt()
                val current=v.tag.toString().toInt()
                val lineTag=if(previous>current) current*10+previous else previous*10+current
                //判断是否有这条线
                if(allLineTags.contains(lineTag)){
                    //点亮这个点和这条线
                    hightLightDot(v)
                    mContainer.findViewWithTag<ImageView>(lineTag.toString()).apply {
                        visibility=View.VISIBLE
                        doneView.add(this)
                    }
                }
            }
        }
    }
    fun hightLightDot(v:ImageView){
        v.visibility=View.VISIBLE
        builder.append(v.tag)
        doneView.add(v)
        lastSDot=v
    }
    fun getLocationOnCons(event: MotionEvent?)= Point().apply {
            x=(event?.x!!-mContainer.x).toInt()
            y=(event?.y!!-mContainer.y).toInt()-barHeight
    }
    fun isContained(point: Point):ImageView?{
        for (v in views){
            Rect(v.left,v.top,v.right,v.bottom).apply {
                if (contains(point.x,point.y)){
                    return v
                }
            }
        }
        return null
    }
    fun recoverUI(){
        for (v in doneView){
            v.visibility=View.INVISIBLE
        }
        doneView.clear()
        lastSDot=null
        Log.v("cx","${builder.toString()}")
        builder.clear()

    }
}